<?php
/**
 * 
 * 
 * @version $Id: CParameterComponent.php,v 1.2 2011-05-29 05:37:28 herve Exp $
 * @copyright 2011
 */
class CParameterComponent extends CApplicationComponent
{
	private $_db=null;

	/**
	 * Initializes this application component.
	 * This method is required by the IApplicationComponent interface.
	 */
	public function init()
	{
		parent::init();
		
		if ($this->_db == null){
			throw new CParameterException(Yii::t('parameter','CParameterException.Connection cannot be null.'));
		}
		
		$db = $this->_db;
		$db = Yii::app()->$db;
		ParamDescription::setDbConnection($db);
		ParamHeader::setDbConnection($db);
		ParamValue::setDbConnection($db);
		
	}
	
	public function setConnection($db){
		$this->_db = $db;
	}
	
	public function getConnection(){
		return $this->_db;
	}
	
	public function getParameterDescription($param_mnemonic){
		$desc = ParamDescription::model()->findByAttributes(array('param_mnemonic'=>$param_mnemonic));
		if ($desc == null)
			throw new CParameterException(Yii::t('parameter','Cannot find parameter with id {id}.', array('{id}' => $param_mnemonic)));
		
		return $desc;
	}
	
	public function getAllParameterDescriptions(){
		$desc = ParamDescription::model()->findAll();
		if ($desc == null)
			throw new CParameterException(Yii::t('parameter','Cannot find parameters'));
		
		return $desc;
	}
	
	public function getParametersArray($param_mnemonic){
		$desc = $this->getParameterDescription($param_mnemonic);
		return new CParameter($desc);
	}
	
	public function getAllParametersArray(){
		$descs = $this->getAllParameterDescriptions();
		$p = array();
		foreach ($descs as $desc)
		{
		 	$p[] = new CParameter($desc); 
		}
		return $p;
	}
	
	private function convertValue($header, $value){
		$r = $value->value;
		
		if ($r == null)
			$r = "";
		
		if ($r == "" && $header->column_type != "string")
			return null;
			
		switch($header->column_type)
		{
			case 'integer': return intval($r, 10);
			case 'float': return floatval($r);
			case 'string': return (string)$r;
			case 'date': return CDateTimeParser::parse($r, "yyyy-MM-dd");
			case 'datetime': return CDateTimeParser::parse($r, "yyyy-MM-dd hh:mm:ss");
			case 'hour': return CDateTimeParser::parse($r, "hh:mm:ss");
			case 'boolean': return strcasecmp($r, "true") == 0;
			default: return $r;
		}		
		return $r;
	}
	
}
?>
